<template>
  <div
    v-if="showTemp == 'showList'"
    class="contentBox"
  >
    <div class="btnBox">
      <el-button
        type="primary"
        @click="add"
      >
        新增问题
      </el-button>
    </div>
    <div class="content">
      <div class="leftTree">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        />
      </div>
      <div class="cntTab setScrollbar">
        <template>
          <el-table
            v-loading="loading"
            :data="tableData"
            stripe
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" width="50" align="center" />
            <el-table-column
              prop="name"
              label="问题名称"
            />
            <!--<el-table-column-->
              <!--prop="level"-->
              <!--label="问题级别"-->
              <!--width="100"-->
              <!--align="center"-->
            <!--&gt;-->
              <!--<template slot-scope="scope">-->
                <!--<span>{{ handLevel(scope.row.level) }}</span>-->
              <!--</template>-->
            <!--</el-table-column>-->
            <el-table-column
              prop="create_by"
              label="创建人"
              width="80"
              align="center"
            />
            <el-table-column
              prop="create_time"
              label="创建时间"
              width="140"
              align="center"
            >
              <template slot-scope="{ row }">
                <span>{{
                  new Date(row.create_time)
                    | statusFilter("{y}-{m}-{d} {h}:{i}")
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="date"
              label="操作"
              width="150"
              align="center"
            >
              <template slot-scope="{ row }">
                <el-button
                  type="text"
                  @click="config(row)"
                >
                  流程关联
                </el-button>
                <el-dropdown
                  style="margin-left: 10px"
                  @command="handleCommand"
                >
                  <span class="el-dropdown-link">
                    更多<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      :command="{ opera: 'edit', row: row }"
                      class="el-dropdown-link"
                    >
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item
                      :command="{ opera: 'deleteRow', row: row }"
                    >
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <!-- 分页 -->
        <div class="pageBox">
          <el-pagination
            background
            :current-page.sync="currentPage"
            :page-size="10"
            layout="prev, pager, next, jumper"
            :total="total"
            @current-change="getForm"
          />
        </div>
      </div>
    </div>
    <el-dialog
      :title="addModel ? '新增问题' : '编辑问题'"
      class="yn_dialog"
      :close-on-click-modal="autoCloseModal"
      :visible.sync="addFormVisible"
      width="700px"
      @close="closeProcee"
    >
      <el-form
        ref="addForm"
        label-width="100px"
        :model="addParams"
        label-position="right"
        class="demo-ruleForm paddLr20 textarea200"
      >
        <el-row>
          <el-col :span="20">
            <el-form-item
              prop="name"
              :rules="[
                {
                  required: true,
                  validator: processNameRules,
                  trigger: ['blur']
                }
              ]"
              label="问题名称"
            >
              <el-input
                v-model="addParams.name"
                :maxlength="20"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item
              prop="type"
              label="问题级别"
            >
              <el-select
                v-model="addParams.level"
                class="filter-item"
              >
                <el-option
                  v-for="item in levelOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top: 15px">
          <el-col :span="20">
            <el-form-item
              prop="description"
              label="问题描述"
            >
              <el-input
                v-model="addParams.description"
                type="textarea"
                :rows="3"
                :maxlength="255"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button
          type="primary"
          :loading="buttonLodding"
          @click="turnToAdd"
        >
          确 定
        </el-button>
        <el-button @click="addFormVisible = false">
          取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
  <div
    v-else
    style="height:100%"
  >
    <create-bpmn
      :def-name="defName"
      :def-key="defKey"
      @callData="callData"
      @cb="cb"
    />
  </div>
</template>
<script>
import { Message } from 'element-ui';
import { v4 as uuidv4 } from 'uuid';
import createBpmn from './bpmn/create';
import { parseTime } from '@/utils';
import { MessageBox } from 'element-ui';
export default {
  components: { createBpmn },
  filters: {
    statusFilter(time, cFormat) {
      return parseTime(time, cFormat);
    }
  },
  data() {
    return {
      addDialogVisible: false,
      editDialogVisible: false,
      delDialogVisible: false,
      loading: false,
      addLoading: false,
      editLoading: false,
      currentPage: 1,
      total: 0,
      current: 1,
      deptId: '',
      ruleForm: {},
      searchObj: {
        deptId: ''
      },
      treeData: [],
      tableData: [],
      seleListData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      addModel: true,
      addFormVisible: false,
      page: 1,
      addParams: {
        name: undefined,
        level: '1',
        description: undefined,
        table_name: undefined,
        send_type: 'user'
      },
      autoCloseModal: false,
      buttonLodding: false,
      currUser: JSON.parse(sessionStorage.getItem('user')),
      queryParams: {
        name: ''
      },
      catCode: 'process',
      userSelectOptions: [],
      currProcess: {},
      defName: '',
      defKey: '',
      levelOption: [
        {
          value: '0',
          label: '初级'
        },
        {
          value: '1',
          label: '中级'
        },
        {
          value: '2',
          label: '高级'
        }
      ],
      showTemp: 'showList'
    };
  },
  created() {
    this.getForm();
    this.getTree();
  },
  methods: {
    handLevel(level){
      return level === '0' ? '初级' : level === '1' ? '中级' : '高级'
    },
    // 执行操作
    handleCommand(obj) {
      if (this[obj.opera]) {
        this[obj.opera](obj.row);
      }
    },
    cb() {
      this.showTemp = 'showList';
    },
    callData(data) {
      this.showTemp = 'showList';
      let form = {};
      for (let key in data) {
        form = data[key];
      }
      const params = {
        c_process: {
          bpmn_key: form.key,
          status: '1',
          '@where': {
            'id@eq': this.currProcess.id
          }
        }
      };
      this.COM.jsonsqlForUpdate(params).then(() => {
        this.getForm();
      });
    },
    config(row) {
      this.currProcess = row;
      this.defName = row.name;
      this.defKey = row.bpmn_key;
      this.showTemp = 'showAdd';
    },
    processNameRules(rule, value, callback) {
      if (!value) return callback('请输入');
      callback();
    },
    nameRules(rule, value, callback) {
      var blank = new RegExp(/^[a-zA-Z]\w{5,39}$/);
      if (value) {
        if (!blank.test(value)) {
          return callback(
            new Error(
              '表名只能包含大小写字母、数字和下划线，并且首字符必须为字母，长度6到40'
            )
          );
        } else if (this.addModel) {
          // 新增流程才判断表名是否重复
          const params = {
            'information_schema.columns:data[]': {
              '@column': '*',
              '@where': {
                'table_name@eq': value.trim(),
                'table_schema@in': 'SELECT database()'
              }
            }
          };
          this.COM.jsonsqlForSelect(params).then(res => {
            if (res.data && res.data.length == 0) {
              this.COM.jsonsqlForSelect({
                'c_process:data[]': {
                  '@column': 'id', //定义返回列
                  '@where': {
                    // 查询条件
                    'table_name@eq': value.trim()
                  }
                }
              }).then(res => {
                if (res.data && res.data.length == 0) {
                  callback();
                } else {
                  callback(new Error('表名重复'));
                }
              });
            } else {
              callback(new Error('表名重复'));
            }
          });
        } else {
          callback();
        }
      } else {
        callback('请输入');
      }
    },
    getForm() {
      const params = {
        'c_process:data[]': {
          '@column': '*', //定义返回列
          '@where': {
            // 查询条件
            'cat_code@like': `%${this.catCode}%`,
            'name@like': `%${this.queryParams.name}%`
          },
          '@page': {
            // 分页配置
            '@pageSize': 10,
            '@pageNo': this.currentPage
          },
          '@order': 'create_time-'
        }
      };
      this.COM.jsonsqlForSelect(params)
        .then(res => {
          this.loading = false;
          this.tableData = res.data;
          this.total = parseInt(res.total);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    closeProcee() {
      this.$refs.addForm.resetFields();
    },
    turnToAdd() {
      this.buttonLodding = true
      this.$refs.addForm.validate(value => {
        if (value) {
          this.addParams.cat_code = this.catCode;
          if (this.addModel) {
            this.addParams.id = uuidv4();
            this.addParams.create_by = this.currUser.account;
            this.addParams.create_time = new Date().getTime();
            this.COM.jsonsqlForInsert({
              c_process: [this.addParams]
            }).then(() => {
              this.$message.success('新增成功');
              this.addFormVisible = false;
              this.getForm();
              this.buttonLodding = false
            });
          } else {
            const params = JSON.parse(JSON.stringify(this.addParams));
            params['@where'] = {
              'id@eq': params.id
            };
            delete params.id;
            params.update_by = this.currUser.account;
            params.update_time = new Date().getTime();
            this.COM.jsonsqlForUpdate({
              c_process: params
            }).then(() => {
              this.$message.success('修改成功');
              this.addFormVisible = false;
              this.getForm();
              this.buttonLodding = false
            });
          }
        } else {
          this.buttonLodding = false
        }
      });
    },
    deleteRow(row) {
      const self = this;
      MessageBox.confirm('此操作将永久删除, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const params = {
            c_process: {
              '@where': {
                'id@eq': row.id
              }
            }
          };
          self.COM.jsonsqlForDelete(params).then(() => {
            self.$message.success('删除成功');
            self.getForm();
          });
        })
        .catch(() => {
          Message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    getTree() {
      this.COM.jsonsqlForSelect({
        'sys_classification:data[]': {
          '@column':
            'classification_id:id,pid:parentId,classification_name:label,cate_code:value',
          '@where': {
            'cate_code@like': '%process%'
          }
        }
      })
        .then(res => {
          this.treeData = this.COM.getTreeData(res.data, 1);
        })
        .catch(() => {
          this.treeLoading = false;
        });
    },
    handleNodeClick(data) {
      // 树节点点击方法
      this.currentPage = 1;
      this.catCode = data.value;
      this.getForm();
    },
    add() {
      this.addModel = true;
      this.userList = [];
      this.addParams = {
        name: '',
        level: '1',
        description: '',
        table_name: ''
      };
      this.addFormVisible = true;
    },
    edit(row) {
      this.addParams = {
        id: row.id,
        name: row.name,
        level: row.level,
        description: row.description,
        table_name: row.table_name
      };
      this.addModel = false;
      this.addFormVisible = true;
    },
    handleCurrentChange(val) {
      // 分页跳转
      this.current = val;
      this.getForm();
    }
  }
};
</script>
<style lang="scss" scoped>
.content {
  display: flex;
  height: calc(100% - 56px) !important;
  .leftTree {
    min-width: 200px;
    height: 100%;
    border: 1px solid #dfe6ec;
  }
  .cntTab {
    flex: 1;
    height: 100%;
    border: 1px solid #dfe6ec;
    border-left: none;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #1890ff;
  }
}
</style>
